<template>
  <div class="divBox">
    <el-card class="box-card" shadow="never" :bordered="false">
      <div class="clearfix">
        <el-button size="small" type="primary" @click="onAdd"> 添加包装</el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="tableData.data"
        style="width: 100%"
        class="mt20"
        size="small"
        row-key="id"
      >
        <el-table-column label="ID" type="index" width="60" />

        <el-table-column label="包装名称" prop="packName" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="说明" prop="packExplain" min-width="200" :show-overflow-tooltip="true" />
        <el-table-column label="价格" prop="cost" min-width="100" />
        <el-table-column label="单位" prop="unit" min-width="80" />
        <el-table-column prop="sort" label="排序" min-width="80" />
        <el-table-column label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <a @click="onEdit(scope.row)">编辑</a>
            <el-divider direction="vertical"></el-divider>
            <a @click="handleDelete(scope.row.productPackId, scope.$index)">删除</a>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          background
          :page-sizes="[20, 40, 60, 80]"
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑包装对话框 -->
    <el-dialog
      :title="editData.id ? '编辑包装' : '添加包装'"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="包装名称" prop="packName">
          <el-input v-model="formData.packName" placeholder="请输入包装名称"></el-input>
        </el-form-item>
        <el-form-item label="说明" prop="packExplain">
          <el-input v-model="formData.packExplain" type="textarea" placeholder="请输入说明"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="cost">
          <el-input v-model="formData.cost" placeholder="请输入价格"></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select style="width: 100%" v-model="formData.unit" placeholder="请选择单位">
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.cateName"
              :value="item.cateName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="formData.sort" :min="0" controls-position="right"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
import * as storeApi from '@/api/product.js';
import * as systemGroupDataApi from '@/api/systemGroupData.js';

import { mapGetters } from 'vuex';
import { checkPermi } from '@/utils/permission';
import { handleDeleteTable } from '@/libs/public';

export default {
  name: 'ProductWrapper',
  computed: {
    ...mapGetters(['merPlatProductClassify']),
  },
  data() {
    return {
      unitList: [],
      dialogVisible: false,
      listLoading: false,
      tableData: {
        data: [],
        total: 0,
      },
      tableFrom: {
        page: 1,
        limit: 20,
      },
      editData: {},
      formData: {
        packName: '',
        packExplain: '',
        cost: 0,
        unit: '',
        sort: 0,
      },
      rules: {
        packName: [{ required: true, message: '请输入包装名称', trigger: 'blur' }],
        cost: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
      },
    };
  },
  mounted() {
    // if (!localStorage.getItem('merPlatProductClassify')) this.$store.dispatch('product/getAdminProductClassify');
    this.handlerGetListData({
      gid: 19,
      keywords: null,
      status: null, // 1=开启 2=关闭
      page: 1,
      pageSize: 100,
    });
    this.getList();
  },
  methods: {
    checkPermi,
    handlerGetListData(pram) {
      // 获取列表数据
      systemGroupDataApi.groupDataList(pram).then((data) => {
        const _selfList = [];
        data.list.forEach((_lItem) => {
          _lItem.value = JSON.parse(_lItem.value);
          const _fields = _lItem.value.fields;
          const _rowData = {};
          _fields.map((item) => {
            _rowData.id = _lItem.id;
            _rowData[item.name] = item.value;
          });

          _selfList.push(_rowData);
        });
        this.unitList = _selfList;
      });
    },
    // 列表
    getList(num) {
      this.listLoading = true;
      this.tableFrom.page = num ? num : this.tableFrom.page;
      // 注意：这里使用的是品牌API，实际项目中应该替换为包装相关API
      storeApi
        .productWrapperListApi(this.tableFrom)
        .then((res) => {
          console.log(111, res);

          // 转换品牌数据为包装数据格式
          this.tableData.data = res.list;
          this.tableData.total = res.total;
          this.listLoading = false;
        })
        .catch((res) => {
          this.listLoading = false;
          this.$message.error(res.message);
        });
    },
    pageChange(page) {
      this.tableFrom.page = page;
      this.getList();
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val;
      this.getList();
    },
    // 添加
    onAdd() {
      this.editData = {};
      this.resetForm();
      this.dialogVisible = true;
    },
    // 编辑
    onEdit(row) {
      this.editData = { ...row };
      this.formData = { ...row };
      this.dialogVisible = true;
    },
    // 删除
    handleDelete(id, idx) {
      this.$modalSure('确定要删除该包装吗？').then(() => {
        // 注意：这里使用的是品牌删除API，实际项目中应该替换为包装删除API
        storeApi.productWrapperDeleteApi({ id }).then((res) => {
          this.$message.success('删除成功');
          handleDeleteTable(this.tableData.data.length, this.tableFrom);
          this.getList();
        });
      });
    },
    // 重置表单
    resetForm() {
      this.formData = {
        packName: '',
        packExplain: '',
        cost: 0,
        unit: '',
        sort: 0,
      };
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    // 关闭对话框
    handleClose() {
      this.resetForm();
      this.dialogVisible = false;
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 注意：这里使用的是品牌API，实际项目中应该替换为包装相关API
          const api = this.editData.productPackId ? storeApi.productWrapperUpdateApi : storeApi.productWrapperAddApi;
          // 转换包装数据为品牌API需要的格式
          const submitData = {
            productPackId: this.editData.productPackId,
            packName: this.formData.packName,
            packExplain: this.formData.packExplain,
            cost: this.formData.cost,
            unit: this.formData.unit,
            sort: this.formData.sort,
          };

          api(submitData)
            .then(() => {
              this.$message.success(this.editData.id ? '编辑成功' : '添加成功');
              this.dialogVisible = false;
              this.getList();
            })
            .catch((res) => {
              this.$message.error(res.message);
            });
        }
      });
    },
  },
};
</script>

<style scoped lang="scss"></style>
